<?php
/**
 * helper.func.php
 * @copyright (c) 2011-2020, Hangzhou DOJI Tech Co., Ltd.
 * This is NOT a freeware, use is subject to license terms.
 * @package helper.function.php
 * @link https://www.tingjunapp.com/
 * @author wujun@lanqb.cn
 * @$Id: helper.func.php 310000 2020-11-07 21:13:44 $
 * */

if (!function_exists('service'))
{
    /**
     * get service instance
     * @return \App\Services\Service|array|string|null
     */
    function service() {
        static $service = [];
        if ($service instanceof \App\Services\Service) {
            return $service;
        }
        return new \App\Services\Service();
    }
}

if (!function_exists('repository'))
{
    /**
     * get repository instance
     * @return \App\Repository\Repository|array|string|null
     */
    function repository() {
        static $repository = [];
        if ($repository instanceof \App\Repository\Repository) {
            return $repository;
        }
        return new \App\Repository\Repository();
    }
}

if (!function_exists('enableQueryLog'))
{
    /**
     * enable query log
     * @return bool
     */
    function enableQueryLog() {
        Illuminate\Support\Facades\DB::connection()->enableQueryLog();
        return true;
    }
}

if (!function_exists('getQueryLog'))
{
    /**
     * get query log
     * @param bool $dump
     * @return mixed
     */
    function getQueryLog($dump = false) {
        $logs = Illuminate\Support\Facades\DB::connection()->getQueryLog();
        $dump && dd($logs);
        return $logs;
    }
}

/**
 * 判断当前环境是否为 local
 * @return bool
 */
function isLocal() {
    return env('APP_ENV') === 'local';
}

/**
 * 判断当前环境是否为 dev
 * @return bool
 */
function isDev() {
    return env('APP_ENV') === 'dev';
}

/**
 * 判断当前环境是否为 test
 * @return bool
 */
function isTest() {
    return env('APP_ENV') === 'test';
}

/**
 * 判断当前环境是否为 prod
 * @return bool
 */
function isProd() {
    return env('APP_ENV') === 'prod';
}

/**
 * 判断是否开启 debug
 * @return bool
 */
function isDebug() {
    return env('API_ACCESS') !== false;
}

/**
 * 获取客户端真实IP
 * @return string|null
 */
function getRealIp() {
    $ip = '';
    $server = $_SERVER;
    if (!empty($server['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $server['HTTP_X_FORWARDED_FOR']);
        $ip = $ips[0];
    } elseif (!empty($server['REMOTE_ADDR'])) {
        $ip = $server['REMOTE_ADDR'];
    }
    return $ip ? : request()->getClientIp();
}



